﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using System.Text.RegularExpressions;
using WebUI.Controls;

namespace WebUI
{
    public partial class ProductImage : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            gallery.OnNeedDataSource = gallery_OnNeedDataSource;
            if (!IsPostBack)
            {
                View_CategoryTree categories = View_CategoryTree.GetCategoryTree();
                Utilities.LoadDropDownList(ddlCategory, categories.DefaultView, View_CategoryTree.ColumnNames.Path, View_CategoryTree.ColumnNames.ID);

                gallery.RefreshData();
                updateGrid.Update();
            }
        }

        int productID
        {
            get{
                if(ddlProduct.SelectedValue == "")
                    return 0;
                return int.Parse(ddlProduct.SelectedValue);
            }
        }

        string productName
        {
            get
            {
                if (ddlProduct.SelectedValue == "")
                    return "";
                return ddlProduct.SelectedItem.Text;
            }
        }

        protected void ddlCategory_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            View_WebProducts p = new View_WebProducts();
            p.Search(View_WebProducts.ColumnNames.CategoryPath + " LIKE '%/" + ddlCategory.SelectedValue + "/%'", View_WebProducts.ColumnNames.ID + "," + View_WebProducts.ColumnNames.ProductName,
                View_WebProducts.ColumnNames.ProductName + " asc", 0, 9999);
            Utilities.LoadDropDownList(ddlProduct, p.DefaultView, View_WebProducts.ColumnNames.ProductName, View_WebProducts.ColumnNames.ID);
        }

        protected void ddlProduct_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            gallery.RefreshData();
            updateGrid.Update();
        }

        protected void gallery_OnNeedDataSource(object sender, EventArgs e)
        {
            ProductImages imgs = new ProductImages();
            imgs.Search(ProductImages.ColumnNames.ProductID + "=" + productID + " and " + ProductImages.ColumnNames.Deleted + " = 0", "*", "", 0, 99);

            gallery.DataSource = imgs.DefaultView;
        }

        protected void btnUploadFinish_OnClick(object sender, EventArgs e)
        {
            if (productID == 0)
                return;

            try
            {
                ProductImages imgs = new ProductImages();
                imgs.Search(ProductImages.ColumnNames.ProductID + "=" + productID + " and [" + ProductImages.ColumnNames.Default + "]= 1" + " and " + ProductImages.ColumnNames.Deleted + " = 0", "*", "", 0, 1);
                bool hasDefaultItem = imgs.RowCount > 0;

                imgs.AddNew();

                bool def = true;
                string thumbUrl = "";
                string originalUrl = "";

                if (hasDefaultItem)
                    def = false;

                string dir = Utilities.GetConfigAppSetting("ProductImagePath");
                string dirMobile = Utilities.GetConfigAppSetting("MobileImagePath");
                if (!System.IO.File.Exists(Server.MapPath(dir)))
                    System.IO.Directory.CreateDirectory(Server.MapPath(dir));
                if (!System.IO.File.Exists(Server.MapPath(dirMobile)))
                    System.IO.Directory.CreateDirectory(Server.MapPath(dirMobile));

                dir += "/" + productID.ToString();
                dirMobile += "/" + productID.ToString();
                if (!System.IO.File.Exists(Server.MapPath(dir)))
                    System.IO.Directory.CreateDirectory(Server.MapPath(dir));
                if (!System.IO.File.Exists(Server.MapPath(dirMobile)))
                    System.IO.Directory.CreateDirectory(Server.MapPath(dirMobile));

                string validName = Regex.Replace(productName, "[~!@#$%^&*()'\"?{}]", "_");

                string fileName = dir + "/" + validName + System.IO.Path.GetFileName(Server.UrlDecode(hidThumbnail.Value));
                thumbUrl = productID.ToString() + "/" + validName + System.IO.Path.GetFileName(Server.UrlDecode(hidThumbnail.Value));
                System.IO.File.Copy(Server.MapPath(Server.UrlDecode(hidThumbnail.Value)), Server.MapPath(fileName));
                try { System.IO.File.Delete(Server.MapPath(Server.UrlDecode(hidThumbnail.Value))); }
                catch (Exception ex) { }

                fileName = dir + "/" + validName + System.IO.Path.GetFileName(Server.UrlDecode(hidPicture.Value));
                originalUrl = productID.ToString() + "/" + validName + System.IO.Path.GetFileName(Server.UrlDecode(hidPicture.Value));
                System.IO.File.Copy(Server.MapPath(Server.UrlDecode(hidPicture.Value)), Server.MapPath(fileName));
                try { System.IO.File.Delete(Server.MapPath(Server.UrlDecode(hidPicture.Value))); }
                catch (Exception ex) { }

                System.Drawing.Image srcBitmap = new System.Drawing.Bitmap(Server.MapPath(Server.UrlDecode(Utilities.GetConfigAppSetting("ProductImagePath") + "/" + thumbUrl)));
                System.Drawing.Image bmp = ImageProcessor.ScaleImage(srcBitmap, 70);
                string fileNameMobile = dirMobile + "/" + validName + System.IO.Path.GetFileName(Server.UrlDecode(hidThumbnail.Value));
                bmp.Save(Server.MapPath(fileNameMobile));

                ProductImages.AddNewImage(def, productID, hidDesc.Value, originalUrl, thumbUrl);
                gallery.RefreshData();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("ProductImage.aspx.cs", "btnUploadFinish_OnClick", ex.StackTrace);
            }
        }

        protected void gallery_OnDeletePicture(object sender, GalleryItemEventArgs e)
        {
            ProductImages.DeleteById(e.Id);
            
        }

        protected void gallery_OnSetDefaultPicure(object sender, GalleryItemEventArgs e)
        {
            ProductImages.SetDefaultPicture(e.Id);
            
        }

        protected void gallery_OnRenamePicture(object sender, GalleryEditItemEventArgs e)
        {
            ProductImages.Rename(e.Id, e.NewName);
        }
    }
}